Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:

  1. "3+2*2" = 7
  2. " 3/2 " = 1
  3. " 3+5 / 2 " = 5

Note: Do not use the eval built-in library function.

Solution:

  1. public class Solution {
  2. public int calculate(String s) {
  3. if (s == null || s.length() == 0)
  4. return 0;
  5. s = "+" + s + "+";
  6. char sign = '+';
  7. char[] a = s.toCharArray();
  8. int n = s.length(), res = 0, num = 0;
  9. Stack<Integer> stack = new Stack<Integer>();
  10. for (int i = 0; i < n; i++) {
  11. if (Character.isDigit(a[i]))
  12. num = num * 10 + a[i] - '0';
  13. if (isOperator(a[i])) {
  14. if (sign == '+') stack.push(num);
  15. if (sign == '-') stack.push(-num);
  16. if (sign == '*') stack.push(stack.pop() * num);
  17. if (sign == '/') stack.push(stack.pop() / num);
  18. num = 0;
  19. sign = a[i];
  20. }
  21. }
  22. for (int i : stack)
  23. res += i;
  24. return res;
  25. }
  26. boolean isOperator(char c) {
  27. return c == '+' || c == '-' || c == '*' || c == '/';
  28. }
  29. }